<?php

declare(strict_types=1);

namespace app\model;

use think\facade\Db;
use think\Model;

/**
 * 
 *
 * @mixin \think\Model
 * @property int $id
 * @property int $agent_id 代理商id
 * @property string $dateymd
 * @property int $income
 * @property int $payout
 * @property int $estimate_amount 预估佣金
 * @property int $settle_amount 今日结算
 * @property int $order_num 订单数
 * @property int $trade_amount 交易额
 * @property int $except_settle_estimate_amount 未结算 扣除已结算的estimate_amount
 */
class AgentFinanceDaily extends CommonModel
{
    /*
    dateymd 格式为 2021-11-11
    */
    public function increase($agentId, $dateymd, $income, $payout, $profit)
    {
        return $this->where('agent_id', $agentId)
                    ->where('dateymd', $dateymd)
                    ->inc('income', $income)
                    ->inc('payout', $payout)
                    ->inc('profit', $profit)
                    ->update();
    }

    /*
    减少
    */
    public function decrease($agentId, $dateymd, $income, $payout, $profit)
    {
        return $this->where('agent_id', $agentId)
                    ->where('dateymd', $dateymd)
                    ->dec('income', $income)
                    ->dec('payout', $payout)
                    ->dec('profit', $profit)
                    ->update();
    }

    /*
     初始化 创建代理商时候
    */
    public function initDaily($agentId)
    {
        $dateymd = date('Y-m-d');
        $tomorrow = date('Y-m-d', strtotime('+1 day'));

        $table = $this->getTable();
        $sql = <<<sql
        insert ignore into {$table} (agent_id,dateymd) values ({$agentId},{$dateymd}), ({$agentId},{$tomorrow})
sql;

        return Db::execute($sql);
    }

    public function initBatchDaily($dateymd = '')
    {
        if (!$dateymd) {
            $dateymd = date('Y-m-d', strtotime('+1 day'));
        }
        $table = $this->getTable();
        $sql = <<<sql
        insert ignore into {$table} (agent_id,dateymd) select id as agent_id,'{$dateymd}' as dateymd from agent where is_deleted=0
sql;

        return Db::execute($sql);
    }
}
